package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {


    @Resource
    AddressBookMapper addressBookMapper;


    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }


    /**
     * @param addressBookUpsertReqDTO
     * @description: 添加地址簿
     * @author: xushuaihang
     * @Date: 2024/8/18 21:09
     * @param:
     * @return: void
     **/
    @Override
    public void addAddress(AddressBookUpsertReqDTO addressBookUpsertReqDTO) {

        Long userId = UserContext.currentUserId();


        if(addressBookUpsertReqDTO.getIsDefault() == 1){
           lambdaUpdate().eq(AddressBook::getUserId, userId)
                    .set(AddressBook::getIsDefault, 0).update();
        }
        String[] split = addressBookUpsertReqDTO.getLocation().split(",");
        AddressBook addressBook = BeanUtil.toBean(addressBookUpsertReqDTO, AddressBook.class);

        addressBook.setLon(Double.parseDouble(split[0]));
        addressBook.setLat(Double.parseDouble(split[1]));
        addressBook.setUserId(userId);

        int insert = baseMapper.insert(addressBook);

        if(insert <= 0){
            throw new ForbiddenOperationException("添加地址簿失败！");
        }

    }

    @Override
    public PageResult<AddressBookResDTO> page(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {

        Page<AddressBook> page = PageUtils.parsePageQuery(addressBookPageQueryReqDTO, AddressBook.class);

        LambdaQueryWrapper<AddressBook> queryWrapper = Wrappers.<AddressBook>lambdaQuery().eq(AddressBook::getUserId, UserContext.currentUserId());
        Page<AddressBook> serveTypePage = addressBookMapper.selectPage(page, queryWrapper);
        return PageUtils.toPage(serveTypePage, AddressBookResDTO.class);

    }

    /**
     * @description: 修改地址簿
     * @author: xushuaihang
     * @Date: 2024/8/19 10:25
     * @param:
     * @param id
     * @param addressBookUpsertReqDTO
     * @return: void
    **/
    @Override
    public void updateAddress(Long id, AddressBookUpsertReqDTO addressBookUpsertReqDTO) {

        String[] split = addressBookUpsertReqDTO.getAddress().split(",");
        AddressBook addressBook = BeanUtil.toBean(addressBookUpsertReqDTO, AddressBook.class);
        addressBook.setLon(Double.valueOf(split[0]));
        addressBook.setLat(Double.valueOf(split[1]));
        addressBook.setId(id);

        if(addressBookUpsertReqDTO.getIsDefault() == 1){
            Long userId = UserContext.currentUserId();
            lambdaUpdate().eq(AddressBook::getUserId, userId)
                    .set(AddressBook::getIsDefault, 0).update();
        }

        int i = baseMapper.updateById(addressBook);

        if(i <= 0){
            throw new ForbiddenOperationException("更新失败！");
        }

    }

    /**
     * @description:  批量删除
     * @author: xushuaihang
     * @Date: 2024/8/19 19:28
     * @param:
     * @param ids
     * @return: void
    **/
    @Override
    public void batchDel(String[] ids) {

        List<Long> idList = Arrays.stream(ids)
                .map(Long::parseLong) // 将 String 转换为 Long
                .collect(Collectors.toList());

        addressBookMapper.deleteBatchIds(idList);


    }


    @Transactional
    @Override
    public void defaultAddr(Integer flag, Long id) {

        Long userId = UserContext.currentUserId();
        lambdaUpdate().eq(AddressBook::getUserId, userId)
                .set(AddressBook::getIsDefault, 0).update();

        boolean update = lambdaUpdate().set(AddressBook::getIsDefault, flag)
                .eq(AddressBook::getId, id).update();

    }

    @Override
    public AddressBook defaultAddress() {

        Long userId = UserContext.currentUserId();

        LambdaQueryWrapper<AddressBook> eq = new QueryWrapper<AddressBook>().lambda()
                .eq(AddressBook::getUserId, userId).eq(AddressBook::getIsDefault, 1);

        AddressBook addressBook = baseMapper.selectOne(eq);

        return addressBook;
    }


}
